#!/usr/bin/perl -w

BEGIN  {
	if(!exists($::ENV{TRUECL_CFG})) {
		print STDERR "Error: TRUECL_CFG environment variable must be defined.\n";
		exit 1;
	}
}

use strict;
use Data::Dumper;
use Crypt::RSA; 
use Sys::Hostname;
use Digest::SHA1;

	if(! -d "$::ENV{TRUECL_CFG}/pki") {
		if(! mkdir("$::ENV{TRUECL_CFG}/pki")) {
			print STDERR "Unable to create directory '$::ENV{TRUECL_CFG}/pki':\n";
			print STDERR "$!\n";
			exit 1;
		}
		print "Created directory '$::ENV{TRUECL_CFG}/pki' to hold RSA key pairs.\n";
	}
	if(! -d "$::ENV{TRUECL_CFG}/keys") {
		if(! mkdir("$::ENV{TRUECL_CFG}/keys")) {
			print STDERR "Unable to create directory '$::ENV{TRUECL_CFG}/keys':\n";
			print STDERR "$!\n";
			exit 1;
		}
		print "Created directory '$::ENV{TRUECL_CFG}/keys' to hold key/window pairs.\n";
	}

	#################################################################
	# Default number of bits is 512 for RSA.			#
	#################################################################

	$::bits=512;
	if($::ARGV[0] && $::ARGV[0] =~ /^\d+$/) {
		$::bits=$::ARGV[0];
	}
	$::host=hostname;

	$|=1;
	if(!chdir("$::ENV{TRUECL_CFG}/pki")) {
		print STDERR "Unable to change directory to '$::ENV{TRUECL_CFG}/pki':\n";
		print STDERR "$!\n";
		exit 1;
	}

	if(! -f "$::host.public") {
		print "Generating RSA key pair [$::bits bits] - please wait...";
		$::rsa=new Crypt::RSA;
		($::public, $::private) = $::rsa->keygen( Size => $::bits, Armour => 1, Verbose => 1 ); 

		print "Done.\n";
		print "Writing RSA files - please wait...";
		$::public->write(Filename => "$::host.public");
		$::private->write(Filename => "$::host.private");
		print "Done.\n";
	} else {
		print "RAS Key pair for $::host already exists.\n";
	}

	exit(0) if -f "$::ENV{TRUECL_CFG}/keys/$::host.key";

	if(!chdir("$::ENV{TRUECL_CFG}/keys")) {
		print STDERR "Unable to change directory to '$::ENV{TRUECL_CFG}/keys':\n";
		print STDERR "$!\n";
		exit 1;
	}

	#################################################################
	# Read in the contents of the private key and generate a SHA1 	#
	# from it to act as a key.					#
	#################################################################

	if(!open($::fd,"$::ENV{TRUECL_CFG}/pki/$::host.private")) {
		print STDERR "Unable to open '$::ENV{TRUECL_CFG}/pki/$::host.private':\n";
		print STDERR "$!\n";
		exit 1;
	}

	$::sha1=Digest::SHA1->new;
	$::sha1->addfile($::fd);
	close($::fd);
	$::digest=$::sha1->hexdigest;

	if(!open($::fd2,">$::host.key")) {
		print STDERR "Unable to open '$::ENV{TRUECL_CFG}/keys/$::host.key':\n";
		print STDERR "$!\n";
		exit 1;
	}
	print $::fd2 "$::digest\n127\n";
	close($::fd2);
	print "Key/window key pair generated for $::host\n";
	exit(0);

